import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_swiper_view/flutter_swiper_view.dart';
import 'package:http/http.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:untitled/utils/request.dart';

import '../net/request.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _HomePageState();
  }
}

class _HomePageState extends State<HomePage> {
  List<Map<String, dynamic>> swiperList = [];
  List<Map<String, dynamic>>? articleList = [];
  int pageNumber = 0; // 用于分页的页码变量

  ScrollController _scrollController = ScrollController();

  void getBannerList() async {
    var response = await NetworkService().get('/banner/json');
    if (response.data != null &&
        response.data is Map<String, dynamic> &&
        response.data.containsKey('data')) {
      final dataList = response.data['data'] as List<dynamic>;
      setState(() {
        swiperList = dataList.cast<Map<String, dynamic>>();
      });
    } else {
      // 处理没有数据或数据为空的情况
      print('No data received from the API.');
    }
  }

  Future getArticleList() async {
    var response = await NetworkService().get('/article/list/$pageNumber/json');
    final dataList = response.data['data']['datas'] as List<dynamic>;
    setState(() {
      if (articleList == null) {
        articleList = dataList.cast<Map<String, dynamic>>();
      } else {
        articleList!.addAll(dataList.cast<Map<String, dynamic>>());
      }
      // 根据获取的数据长度判断是否还有更多数据
      if (dataList.length < 20) {
        setState(() {
          isLoadMore = false;
        });
      } else {
        setState(() {
          isLoadMore = true;
          pageNumber++; // 增加页码准备下一次加载更多
        });
      }
    });
    print('_________________$articleList');
  }

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        print("滚动到底部了");
        getArticleList();
      }
    });
    getBannerList();
    getArticleList();
  }

  String title = '我是首页';

  void onTap(int index) {
    print("点击了$index");
  }

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  bool isLoadMore = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('首页'), actions: <Widget>[
          //导航栏右侧菜单
          IconButton(icon: Icon(Icons.add_alarm), onPressed: () {}),
          IconButton(icon: Icon(Icons.add_a_photo), onPressed: () {}),
        ],),
        body: SafeArea(
            child: SmartRefresher(
                controller: _refreshController,
                onRefresh: () async {
                  pageNumber = 0; // 刷新时重置页码
                  await getArticleList();
                  _refreshController.refreshCompleted();
                },
                onLoading: () async {
                  print("——————————————————加载更多");
                  if (!isLoadMore) {
                    setState(() {
                      isLoadMore = true;
                    });
                    await getArticleList();
                    setState(() {
                      isLoadMore = false;
                    });
                  }
                },
                enablePullDown: true,
                enablePullUp: true,
                header: const WaterDropHeader(),
                footer: const ClassicFooter(),
                child: Column(
                  children: [
                    SizedBox(
                      width: double.infinity,
                      height: 150,
                      child: Swiper(
                        itemBuilder: (context, index) {
                          return Image.network(
                            swiperList[index]['imagePath'],
                            fit: BoxFit.fill,
                          );
                        },
                        itemCount: swiperList.length,
                        pagination: const SwiperPagination(),
                        // control: const SwiperControl(),
                        loop: true,
                        onTap: onTap,
                      ),
                    ),
                    Expanded(
                        child: ListView.builder(
                      // itemBuilder: (context, index) {
                      //   return _listItemView(context, index);
                      // },
                      itemCount: articleList!.length + (isLoadMore ? 1 : 0),
                      itemBuilder: (context, index) {
                        if (index == articleList?.length) {
                          // 当滚动到列表底部时，显示加载更多
                          return isLoadMore
                              ? Center(child: CircularProgressIndicator())
                              : Center(
                                  child: Text(
                                  "加载更多",
                                ));
                        }
                        return _listItemView(context, index);
                      },
                      // controller: ScrollController()
                      controller: _scrollController,
                    ))
                  ],
                ))));

    // body: );
  }

  Widget _listItemView(BuildContext context, int index) {
    return InkWell(
      onTap: () {
        Navigator.pushNamed(context, '/about', arguments: title);
      },
      child: Container(
          margin: const EdgeInsets.only(top: 5, bottom: 5, left: 10, right: 10),
          padding: const EdgeInsets.only(top: 5, bottom: 5, left: 8, right: 8),
          decoration: BoxDecoration(
              border: Border.all(color: Colors.black, width: 0.5),
              borderRadius: BorderRadius.circular(5)),
          child: Column(children: [
            Row(
              children: [
                Container(
                  decoration: const BoxDecoration(
                    shape: BoxShape.circle,
                  ),
                  clipBehavior: Clip.antiAlias,
                  child: Image.network(
                    'https://img2.baidu.com/it/u=2102877950,2155081877&fm=253&fmt=auto&app=120&f=JPEG?w=30&h=30',
                    fit: BoxFit.cover,
                    width: 30,
                    height: 30,
                  ),
                ),
                Container(
                  margin: const EdgeInsets.only(left: 10),
                  child: Text('${articleList?[index]['author']}' ?? ''),
                ),
                const Expanded(child: SizedBox()),
                Text("${articleList?[index]['niceShareDate']}" ?? ''),
                Container(
                  margin: const EdgeInsets.only(left: 10),
                  child: const Text(
                    "置顶",
                    style: TextStyle(
                      color: Colors.green,
                      fontSize: 12,
                      fontWeight: FontWeight.w900,
                    ),
                  ),
                )
              ],
            ),
            Row(
              children: [
                Expanded(
                  child: Text(
                    '${articleList?[index]['title']}' ?? '',
                    softWrap: true,
                    maxLines: 2,
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ],
            ),
            Row(
              children: [
                const Text(
                  "分类",
                  style: TextStyle(
                      color: Colors.greenAccent,
                      fontSize: 12,
                      fontWeight: FontWeight.normal),
                ),
                const Expanded(child: SizedBox()),
                Image.asset(
                  'assets/images/shoucang.png',
                  width: 20,
                  height: 20,
                )
              ],
            )
          ])),
    );
  }
}
